package com.yincb;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;

public class HttpsProxyServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {


        // 第一步：获取代理的请求相关信息
        // 1、获取请求信息 HOST URI
        // 2、获取请求头信息
        // 3、获取请求体信息

        HttpMethod method = request.method();
        String uri = request.uri();
        String host = request.headers().get("Host");

        System.out.println(String.format("https://%s%s", host, uri));

        // 第二步：代理请求
        // 1、通过HTTP请求客户端工具，代理请求
        // 2、获取代理请求响应消息
        // 3、响应客户端代理请求的响应
        URL url = new URL(String.format("https://%s%s", host, uri));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method.name());
        List<Map.Entry<String, String>> entries = request.headers().entries();
        for (Map.Entry<String, String> entry : entries) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        FullHttpResponse response =
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                        HttpResponseStatus.valueOf(conn.getResponseCode()),
                        Unpooled.copiedBuffer(convert(conn.getInputStream())));

        // 响应头
        for (int i = 1; ; i++) {
            String headerName = conn.getHeaderFieldKey(i);
            String headerValue = conn.getHeaderField(i);
            if (headerName == null && headerValue == null) {
                break;
            }
            response.headers().set(headerName, headerValue);
        }

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }




    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
        }
    }


    private void sendError(ChannelHandlerContext ctx, HttpResponseStatus responseStatus) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                responseStatus,
                Unpooled.copiedBuffer("Failure:" + responseStatus.toString() + "\r\n", StandardCharsets.UTF_8));
        response.headers().set(CONTENT_TYPE, "test/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }


    /**
     * inputStream转byte
     * @param inputStream
     * @return
     */
    public static byte[] convert(InputStream inputStream) {
        try {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            return buffer.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
